<?php

class Application_Model_Mapper_TurncacheMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable()
	{
		
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Turncache');
		}
		return $this->_dbTable;
		
	}

	public function add(Application_Model_Turncache $turn)
	{		
		$now = new DateTime();
		
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchID($generatedid);
		if(empty($generatedidcheck)){
		
			$data = array(
					'id' => $generatedid,
					'startpunktobjekt' => $turn->getStartpunktobjekt(),
					'startpunktid' => $turn->getStartpunktid(),
					'zielpunktobjekt' => $turn->getZielpunktobjekt(),
					'zielpunktid' => $turn->getZielpunktid(),	
					'entfernung' => $turn->getEntfernung()	
			);
	
			$this->getDbTable()->insert($data);
			return $generatedid;
		}
		else{
			$this->add($turn);
		}
		
	}
	
	public function fetchobjekts($objektatyp, $objektaid, $objektbtyp, $objektbid)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('turncache');
		$entry->where('turncache.startpunktobjekt = ?', $objektatyp);
		$entry->where('turncache.startpunktid = ?', $objektaid);
		$entry->where('turncache.zielpunktobjekt = ?', $objektbtyp);
		$entry->where('turncache.zielpunktid = ?', $objektbid);
		$entry->orwhere('turncache.startpunktobjekt = ?', $objektbtyp);
		$entry->where('turncache.startpunktid = ?', $objektbid);
		$entry->where('turncache.zielpunktobjekt = ?', $objektatyp);
		$entry->where('turncache.zielpunktid = ?', $objektaid);
		return $entry->query()->fetch();
	}
	
	public function fetchID($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('turncache');
		$entry->where('turncache.id = ?', $id);
		return $entry->query()->fetch();
	}

}




